package com.train.servlet;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.tea.TeaException;
import com.train.utils.CodeGenerate;
import com.train.utils.SmsServiceUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import redis.clients.jedis.Jedis;

import java.io.IOException;

@WebServlet("/SMSCode")
public class SmsCodeServlet extends HttpServlet {

    //new一个Jedis对象，给其中传入Redis服务器的IP地址和Redis服务器监听的端口号
    //Jedis是库中的一个类，代表了Redis服务器连接
    private Jedis jedis=new Jedis("127.0.0.1",6379);
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // This file is auto-generated, don't edit it. Thanks.

        String phone = request.getParameter("phone");
        //生成一个验证码
        int code = CodeGenerate.generateCode();
        HttpSession session = request.getSession();
        JSONObject json = new JSONObject();
        try {
            SmsServiceUtil.sms(phone,code);
            json.put("code",200);
            json.put("msg","OK");
            System.out.println("sms="+code);
            System.out.println(json.toString());
            //存储在Redis数据库中，并将code转化为String类型
            jedis.set(phone,code+"");
            System.out.println(jedis.get(phone));
            //给phone这个键设置一个过期时间
            jedis.expire(phone,60*5);
        } catch (Exception e) {
            json.put("code",300);
            json.put("msg","error");
        }
        response.getWriter().write(json.toString());
    }
}
